<template>
  <y-dialog @open="open" @close="emit('close')" width="1000px" append-to-body>
    <div style="border: 1px solid var(--el-border-color); padding: 10px">
      <div>
        <h3><strong>预置条件</strong></h3>
        <h4>{{ form.precondition }}</h4>
      </div>
      <div>
        <h3><strong>操作步骤</strong></h3>
        <el-table
          v-loading="loading"
          :data="form.steps"
          border
          style="width: 100%"
        >
          <el-table-column prop="id" label="序号" width="100" align="center" />
          <el-table-column prop="step" label="步骤" />
          <el-table-column prop="exp" label="预期" />
          <el-table-column
            prop="pcap"
            label="样本数据"
            v-if="['8'].includes(form.type)"
          />
          <el-table-column
            prop="rule"
            label="样本规则"
            v-if="['8'].includes(form.type)"
          />
          <el-table-column prop="actual" label="实际值">
            <template #default="scope">
              <el-input v-model="scope.row.actual" type="textarea" :rows="1" />
            </template>
          </el-table-column>
          <el-table-column prop="result" label="测试结果">
            <template #default="scope">
              <y-select
                v-model="scope.row.result"
                placeholder="请选择执行结果"
                :options="tms_tc_result"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="emit('close')">取消</el-button>
      </div>
    </template>
  </y-dialog>
</template>

<script setup name="Manual">
import useUserStore from "@/store/modules/user";
const { proxy } = getCurrentInstance();

const emit = defineEmits(["submited", "close"]);

const { tms_tc_result } = proxy.useDict("tms_tc_result");

const loading = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    job: undefined,
    job_execution: undefined,
    nopaginate: true,
  },
});

const { queryParams, form } = toRefs(data);

const props = defineProps({
  id: { type: String, default: null },
  updateJob: { type: Function, default: undefined },
  getJobLog: { type: Function, default: undefined },
  listJobLog: { type: Function, default: undefined },
  updateJobLog: { type: Function, default: undefined },
  updateExecutionJob: { type: Function, default: undefined },
});

/** 打开对话框事件 */
function open() {
  loading.value = true;
  props.getJobLog(props.id).then((res) => {
    form.value = res.data;
    // 获取用例开始执行时间
    form.value.run_time = new Date(+new Date() + 8 * 3600 * 1000).toISOString();
    // 初始化执行结果
    form.value.steps.some((val) => {
      val.result = null;
    });
    queryParams.value.job = form.value.job.id;
    queryParams.value.job_execution = form.value.job_execution.id;
    loading.value = false;
  });
}

/** 提交按钮事件 */
function submit() {
  let fail = 0;
  let block = 0;
  let stepUnFinishedList = [];
  // 统计各步骤的执行情况
  form.value.steps.some((val) => {
    if (val.result == null || val.result === "") {
      stepUnFinishedList.push(val.step);
    } else {
      fail = val.result == "1" ? fail + 1 : fail;
      block = val.result == "2" ? block + 1 : block;
    }
  });
  if (stepUnFinishedList.length != 0) {
    proxy.$modal.msgWarning(`步骤"${stepUnFinishedList}"，尚未执行`);
  } else {
    loading.value = true;
    // 将用例执行结果，转换为用例执行状态
    form.value.status = fail + block == 0 ? "3" : form.value.status;
    form.value.status = fail > 0 ? "4" : form.value.status;
    form.value.status = block > 0 ? "5" : form.value.status;

    if (form.value.status != "3") {
      form.value.analysis = "0";
    } else {
      form.value.analysis = null;
    }

    // 获取用例执行完成时间
    form.value.finished = new Date(+new Date() + 8 * 3600 * 1000).toISOString();

    useUserStore()
      .getInfo()
      .then((res) => {
        const newJobLog = form.value;
        newJobLog.job = newJobLog.job.id;
        newJobLog.job_execution = newJobLog.job_execution.id;
        newJobLog.executor = res.data.user.id;

        props.updateJobLog(newJobLog).then(() => {
          props.listJobLog(queryParams.value).then((res) => {
            let norun = res.data.filter((tc) => tc.status === "0").length;
            let percentage = 100 - ((norun / res.total) * 100).toFixed(0);
            // 更新任务进度和状态
            if (percentage < 100) {
              props
                .updateJob({
                  id: queryParams.value.job,
                  percentage: percentage,
                  partial: true,
                })
                .then(() => {
                  loading.value = false;
                  proxy.$modal.msgSuccess("执行成功");
                  submited();
                });
            } else {
              const finished = new Date(
                +new Date() + 8 * 3600 * 1000
              ).toISOString();
              props
                .updateJob({
                  id: queryParams.value.job,
                  percentage: percentage,
                  finished: finished,
                  status: "3",
                  partial: true,
                })
                .then(() => {
                  props
                    .updateExecutionJob({
                      id: queryParams.value.job_execution,
                      finished: finished,
                      status: "3",
                      partial: true,
                    })
                    .then(() => {
                      loading.value = false;
                      proxy.$modal.msgSuccess("执行成功");
                      submited();
                    });
                });
            }
          });
        });
      });
  }
}

/** submited事件 */
function submited() {
  emit("submited");
  emit("close");
}
</script>
